package com.lucas.rpc.framework.transport.socket;

import com.lucas.rpc.framework.entity.RpcRequest;
import com.lucas.rpc.framework.entity.RpcResponse;
import com.lucas.rpc.framework.entity.RpcServiceConfig;
import com.lucas.rpc.framework.entity.URL;
import com.lucas.rpc.framework.handler.RpcRequestHandler;
import com.lucas.rpc.framework.server.register.FakeRemoteRegister;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: LiuCheng
 * @description:
 * @date: 2023-12-04 15:52
 **/
public class SocketRpcServer {

    private RpcServiceConfig rpcServiceConfig;

    public void start(){

        try (ServerSocket server = new ServerSocket()) {
            String host = InetAddress.getLocalHost().getHostAddress();
            server.bind(new InetSocketAddress(host, 8080));
            Socket socket;
            while ((socket = server.accept()) != null) {
                try (ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                     ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream())) {
                    RpcRequest rpcRequest = (RpcRequest) objectInputStream.readObject();
                    RpcRequestHandler rpcRequestHandler = new RpcRequestHandler();
                    Object result = rpcRequestHandler.handle(rpcRequest);
                    objectOutputStream.writeObject(RpcResponse.success(result));
                    objectOutputStream.flush();
                } catch (IOException | ClassNotFoundException e) {
                }
            }
        } catch (IOException e) {
        }
    }
}
